<template>
  <div>
    <!-- 三级分类结构 -->
    <Category :scene="scene"></Category>
    <el-card style="margin: 10px 0">
      <!-- vif和vshow都可以实现显示与隐藏 -->
      <div v-show="scene === 0">
        <el-button
          type="primary"
          size="default"
          @click="addSpu"
          icon="Plus"
          :disabled="!categoryStore.c3Id"
        >
          添加SPU
        </el-button>
        <!-- 展示已有SPU数据 -->
        <el-table :data="records" style="margin: 10px 0" border stripe>
          <el-table-column
            label="序号"
            border
            type="index"
            align="center"
            width="80px"
          ></el-table-column>
          <el-table-column
            label="SPU名称"
            prop="spuName"
            border
          ></el-table-column>
          <el-table-column
            label="SPU描述"
            prop="description"
            border
            show-overflow-tooltip
          ></el-table-column>
          <el-table-column label="SPU操作" border>
            <!-- row即为已有的SPU对象 -->
            <template #="{ row }">
              <el-button
                type="primary"
                size="small"
                @click="addSku(row)"
                icon="Plus"
                title="添加SKU"
              ></el-button>
              <el-button
                type="primary"
                size="small"
                @click="updateSpu(row)"
                icon="Edit"
                title="修改已有的SKU"
              ></el-button>
              <el-button
                type="primary"
                size="small"
                @click="findSKu(row)"
                icon="View"
                title="查看SKU列表"
              ></el-button>
              <el-popconfirm
                width="200px"
                :title="`确认删除？${row.spuName}`"
                @confirm="deleteSpu(row)"
              >
                <template #reference>
                  <el-button
                    type="primary"
                    size="small"
                    @click=""
                    icon="Delete"
                    title="删除SKU列表"
                  ></el-button>
                </template>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页器 -->
        <el-pagination
          v-model:current-page="pageNo"
          v-model:page-size="pageSize"
          :page-sizes="[3, 5, 7, 9]"
          :background="true"
          layout=" prev, pager, next, jumper,->,sizes,total"
          :total="total"
          @current-change="getHasSpu"
          @size-change="changeSize"
        />
      </div>
      <!-- 添加SPU和修改SPU子组件 -->
      <SpuForm
        ref="spuForm"
        v-show="scene === 1"
        @changeScene="changeScene"
      ></SpuForm>
      <!-- 添加SKU的子组件 -->
      <SkuForm
        ref="skuForm"
        @changeScene="changeScene"
        v-show="scene === 2"
      ></SkuForm>
      <!-- dialog对话框：展示已有的SKU数据 -->
      <el-dialog v-model="show" title="SKU列表" width="60%" @close="">
        <el-table :data="skuArr" border stripe>
          <el-table-column prop="skuName" label="SKU名字"></el-table-column>
          <el-table-column prop="price" label="SKU价格"></el-table-column>
          <el-table-column prop="weight" label="SKU重量"></el-table-column>
          <el-table-column prop="skuName" label="SKU图片">
            <template #="{ row }">
              <img
                :src="row.skuDefaultImg"
                alt=""
                style="width: 100px; height: 100px"
              />
            </template>
          </el-table-column>
        </el-table>
      </el-dialog>
    </el-card>
  </div>
</template>

<script lang="ts" setup>
//引入子组件
import SpuForm from './spuForm.vue'
import SkuForm from './skuForm.vue'
//引入分类仓库
import useCategoryStore from '@/store/modules/category'
import { onBeforeUnmount, ref, watch } from 'vue'
import { reqHasSpu, reqSkuList } from '@/apis/product/spu/index'
import type {
  SkuInfoData,
  HasSpuResponseData,
  Records,
  SpuData,
} from '@/apis/product/spu/type'
import { SkuData } from '@/apis/product/spu/type'
import { reqRemoveAttr } from '@/apis/product/attr'
import { ElMessage } from 'element-plus'

let categoryStore = useCategoryStore()
//场景数值
let scene = ref<number>(0) //0显示已有spu 1：添加或修改已有spu 2：添加修改sku
//分页器默认页码
let pageNo = ref<number>(1)
//每一页展示几条数据
let pageSize = ref<number>(3)
//存储已有SPU数据
let records = ref<Records>([])
//存储已有SPU总个数
let total = ref<number>(0)
//子组件实例对象
let spuForm = ref<any>()
//获取子组件实例skuForm
let skuForm = ref<any>()
//存储全部的SKU数据
let skuArr = ref<SkuData[]>([])
//对话框显示与隐藏
let show = ref<boolean>(false)

//监听三级分类Id变化
watch(
  () => categoryStore.c3Id,
  () => {
    //保证有三级分类id才发送数据
    if (!categoryStore.c3Id) {
      return
    }
    getHasSpu()
  },
)

//方法执行：获取三级分类下全部的已有SPU
const getHasSpu = async (pager = 1) => {
  //修改当前页码
  pageNo.value = pager
  let res: HasSpuResponseData = await reqHasSpu(
    pageNo.value,
    pageSize.value,
    categoryStore.c3Id,
  )
  // console.log(res)
  if (res.code === 200) {
    records.value = res.data.records
    total.value = res.data.total
  }
}

//分页器下拉菜单发生变化时触发
const changeSize = () => {
  getHasSpu()
}

//添加新的SPU按钮的回调
const addSpu = () => {
  scene.value = 1
  //初始化spuForm内的数据
  spuForm.value.initAddSpu(categoryStore.c3Id)
}

//子组件通知父组件切换场景的自定义事件
const changeScene = (obj: any) => {
  //子组件SpuForm点击取消变为场景0，展示已有的SPU
  scene.value = obj.flag
  if (obj.params === 'update') {
    //更新留在当前页
    getHasSpu(pageNo.value)
  } else {
    //更新场景数据
    //添加留在第一页
    getHasSpu()
  }
}

//修改已有的SPU按钮的回调
const updateSpu = (row: SpuData) => {
  scene.value = 1
  //调用子组件内的方法
  spuForm.value.initHasSpuData(row)
}

//添加SKU按钮的回调
const addSku = (row: SpuData) => {
  //点击添加sku按钮，切换场景为2
  scene.value = 2
  //初始化skuForm内的数据
  skuForm.value.initSkuData(
    categoryStore.c1Id,
    categoryStore.c2Id,
    categoryStore.c3Id,
    row,
  )
}

//查看SKU列表的数据
const findSKu = async (row: SpuData) => {
  let result: SkuInfoData = await reqSkuList(row.id as number)

  if (result.code === 200) {
    skuArr.value = result.data
    //显示对话框
    show.value = true
  }
}
//删除SPU
const deleteSpu = async (row: SpuData) => {
  let result: any = await reqRemoveAttr(row.id as number)
  if (result.code === 200) {
    ElMessage({
      type: 'success',
      message: '删除成功',
    })
    //获取已有的数据
    //判断剩余SPU数据
    getHasSpu(records.value.length > 1 ? pageNo.value : pageNo.value - 1)
  } else {
    ElMessage({
      type: 'error',
      message: '删除失败',
    })
  }
}

//路由组件销毁前，清空数据
onBeforeUnmount(() => {
  categoryStore.$reset()
})
</script>

<style lang="scss" scoped></style>
